package service

import (
	"admin100/app/dao"
	"admin100/app/model"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"admin100/library/utils"
	"strings"

	"github.com/gogf/gf/os/gtime"
)

var LoginNotice = &loginNoticeService{}

type loginNoticeService struct{}

const LoginNoticeJoinStr = "_^_"

func (s *loginNoticeService) UpdateAndPushLoginNotice(uid int, req *model.SetLoginNoticeReq) bool {
	data := utils.Marshal(*req)
	url := utils.GetCenterURL() + "/set_login_notice"
	if s := utils.HttpRequest(url, string(data)); s == "fail" {
		return false
	}

	noticeLog := model.LoginNotice{
		Id:         req.PlatformId + LoginNoticeJoinStr + req.ChannelId,
		PlatformId: req.PlatformId,
		ChannelId:  req.ChannelId,
		Notice:     req.Notice,
		Time:       int(gtime.Timestamp()),
		UserId:     uid,
	}

	_, err := dao.LoginNotice.FieldsEx("userName").Save(&noticeLog)
	if err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}

	return true

}

func (s *loginNoticeService) BatchSetNotice(uid int, req *model.BatchSetLoginNoticeReq) {
	//todo 改成一次性指请示，而不是单独
	nids := strings.Split(req.Id, ",")
	for _, idStr := range nids {
		list := strings.Split(idStr, LoginNoticeJoinStr)
		if len(list) >= 2 {
			upNoticeReq := model.SetLoginNoticeReq{
				PlatformId: list[0],
				ChannelId:  list[1],
				Notice:     req.Notice,
			}
			s.UpdateAndPushLoginNotice(uid, &upNoticeReq)
		} else {
			defErr.Panic(define.DataOptFail, define.GotMsg(define.ReqDelLoginNoticeErr)+" : "+idStr)
		}
	}
}

func (s *loginNoticeService) Del(uid int, req *model.DelLoginNoticeReq) {
	s.BatchSetNotice(uid, &model.BatchSetLoginNoticeReq{
		Id:     req.IdList,
		Notice: "",
	})

	nids := strings.Split(req.IdList, ",")
	_, err := dao.LoginNotice.Delete(dao.LoginNotice.Columns.PlatformId, nids)
	if err != nil {
		defErr.Panic(define.DataOptFail, err.Error())
	}
}

func (s *loginNoticeService) List(req *model.LoginNoticeListReq) []*model.LoginNotice {
	data, err := dao.LoginNotice.Where(dao.LoginNotice.Columns.PlatformId, strings.Split(req.PlatformIdList, ",")).FindAll()
	defErr.SelectRetPanic(err, data, define.DataOptFail)

	var uids []int
	for _, v := range data {
		uids = append(uids, v.UserId)
	}

	us := dao.MyadminUser.GetUserList(uids)
	for _, v := range data {
		if e, ok := us[v.UserId]; ok {
			v.UserName = e.Name
		}

	}

	return data
}
